package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-05
 */
@Service
@RequiredArgsConstructor
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    private final WechatService wechatService;
    private final TokenService  tokenService;

    private final static List<String> NICK_NAMES = List.of("维什戴尔","黍","逻格斯","娜仁图雅","阿米娅","塑心","佩佩");

    /**
     * 小程序端登录
     *
     * @author I:P Masquerenaʚїɞ
     * @date 2025/6/9
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());

        //2.去数据库查找该openid是否存在
        FamilyMember familyMember = Db.lambdaQuery(FamilyMember.class).eq(FamilyMember::getOpenId, openid).one();

        //3.判断是否是新用户
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember.builder().openId(openid).build();
        }

        //4.获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());

        //5.更新原用户或者插入新用户
        saveOrUpdateFamilyMember(familyMember, phone);

        //6.返回token和昵称
        Map<String,Object> claim = new HashMap<>();
        claim.put("userId", familyMember.getId());
        claim.put("nickName", familyMember.getName());
        String token = tokenService.createToken(claim);

        return new LoginVo(token, familyMember.getName());
    }

    /**
     * 保存或修改用户
     *
     * @author I:P Masquerenaʚїɞ
     * @date 2025/6/9
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember, String phone) {
        if(ObjectUtil.notEqual(familyMember.getPhone(), phone)){
            familyMember.setPhone(phone);
        }

        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }

        String nickName = NICK_NAMES.get((int) (Math.random() * NICK_NAMES.size()));
        familyMember.setName(nickName);
        save(familyMember);
    }
}
